<?php

namespace app\api\controller;

use app\api\BaseController;
use app\api\middleware\Auth;
use think\facade\Db;
use function fast\e;

class Score extends BaseController
{
    /**
     * 控制器中间件 [积分商城]
     * @var array
     */
    protected $middleware = [
        Auth::class => ['except' 	=> [''] ]
    ];

    /**
     * 积分商城首页
     */
    public function index()
    {
        $param = get_params();
        $user = Db::name('user')->where('id',JWT_UID)->find();
        $config = Db::name('config')->where('id',15)->find();
        $conf = unserialize($config['content']);

        //商品列表
        $sort = 'id desc';
        if (!empty($param['price'])) {
            if ($param['price'] == 'up') {
                $sort = 'price desc';
            } else {
                $sort = 'price asc';
            }
        }
        if (!empty($param['sales'])) {
            if ($param['sales'] == 'up') {
                $sort = 'sales desc';
            } else {
                $sort = 'sales asc';
            }
        }
        $goods = Db::name('score_goods')->field('id,thumb,title,price,sales')
            ->where(['status'=>1,'delete_time'=>0])->order($sort)->select()->toArray();

        $return = [
            'score' => $user['score'],
            'explain' => $conf['explain'],
            'goods' => $goods,
        ];
        return success('',$return);
    }

    /**
     * 商品详情
     */
    public function detail()
    {
        $param = get_params();
        $goods = Db::name('score_goods')->where(['id'=>$param['id']])->find();
        $goods['content'] = str_replace('src="/storage','src="'.request()->domain().'/storage',$goods['content']);
        if (!empty($goods['banner'])) {
            $goods['banner'] = Db::name('file')->where([['id','in',$goods['banner']]])->column('filepath');
        }
        return success('',$goods);
    }

    /**
     * 我的地址列表
     */
    public function address()
    {
        $data = Db::name('addr')
            ->field('id,region,address,user_name,mobile,is_sel')
            ->where(['uid'=>JWT_UID,'mark'=>1])
            ->order('id desc')
            ->select();
        return json(['code'=>0,'msg'=>'获取成功','data'=>$data]);
    }

    /**
     * 设置默认地址
     */
    public function setSel()
    {
        if (request()->isPost()) {
            $param = request()->param();
            if (empty($param['id'])) {
                return json(['code'=>1,'msg'=>'参数错误']);
            }

            $data = Db::name('addr')->where(['id'=>$param['id']])->find();
            if (!empty($data['is_sel'])) {
                Db::name('addr')->where(['id'=>$data['id']])->update(['is_sel'=>0]);
            } else {
                $sel_addr = Db::name('addr')->where(['uid'=>JWT_UID,'is_sel'=>1,'mark'=>1])->find();
                if (!empty($sel_addr)) {
                    Db::name('addr')->where(['id'=>$sel_addr['id']])->update(['is_sel'=>0]);
                }
                Db::name('addr')->where(['id'=>$param['id']])->update(['is_sel'=>1]);
            }
            return json(['code'=>0,'msg'=>'操作成功','data'=>'']);
        }
    }

    /**
     * 删除地址
     */
    public function delAddress()
    {
        if (request()->isPost()) {
            $param = request()->param();
            if (empty($param['id'])) {
                return json(['code'=>1,'msg'=>'参数错误']);
            }
            $addr = Db::name('addr')->where(['id'=>$param['id']])->find();
            if (empty($addr)) {
                return json(['code'=>1,'msg'=>'地址已删除']);
            }
            Db::name('addr')->where(['id'=>$param['id']])->delete();
            return json(['code'=>0,'msg'=>'删除成功']);
        }
    }

    /**
     * 获取地址详细信息
     */
    public function getAddrDetail()
    {
        $param = request()->param();
        if (empty($param['id'])) {
            return json(['code'=>1,'msg'=>'参数错误']);
        }
        $data = Db::name('addr')
            ->field('id,region,region_code,address,user_name,mobile,is_sel')
            ->where(['id'=>$param['id']])
            ->find();
        return json(['code'=>0,'msg'=>'获取成功','data'=>$data]);
    }

    /**
     * 添加/修改地址
     */
    public function addAddr()
    {
        if (request()->isPost()) {
            $param = request()->param();
            $insert['uid'] = JWT_UID;
            $insert['region'] = $param['region'];
            $insert['address'] = $param['address'];
            $insert['user_name'] = $param['user_name'];
            $insert['mobile'] = $param['mobile'];
            $insert['is_sel'] = $param['is_sel'];
            if (!empty($param['is_sel'])) {
                $addr = Db::name('addr')->where(['mark'=>1,'uid'=>$insert['uid'],'is_sel'=>1])->find();
                if (!empty($addr)) {
                    Db::name('addr')->where(['id'=>$addr['id']])->update(['is_sel'=>0]);
                }
            }
            if (empty($param['id'])) {
                $insert['create_time'] = time();
                $res = Db::name('addr')->insert($insert);
            } else {
                $res = Db::name('addr')->where(['id'=>$param['id']])->update($insert);
            }
            if (empty($res)) {
                return json(['code'=>1,'msg'=>'操作失败,请稍后再试']);
            }
            return json(['code'=>0,'msg'=>'操作成功']);
        }
    }

    /**
     * 订单确认页
     */
    public function order()
    {
        $param = request()->param();
        $goods = Db::name('score_goods')->field('id,is_mail,thumb,title,price,yun_money,goods_type')
            ->where('id',$param['id'])->find();
        $address = Db::name('addr')
            ->field('id,region,address,user_name,mobile')
            ->where(['uid'=>JWT_UID,'is_sel'=>1])
            ->find();
        if (empty($address)) {
            $address = '';
        }
        $yun = 0;
        if (empty($address['is_mail'])) {
            $yun = $goods['yun_money'];
        }
        $total = $goods['price']+$yun;
        $return = [
            'address' => $address,
            'count' => 1,
            'yun_money' => $yun,
            'total' => $total,
            'goods' => $goods,
        ];
        return success('',$return);
    }

    /**
     * 订单列表
     */
    public function orderList()
    {
        $param = request()->param();
        $sql[] = ['delete_time','=',0];
        $sql[] = ['uid','=',JWT_UID];
        $sql[] = ['status','=',$param['status']];
        $data = Db::name('score_order')->where($sql)->order('id desc')->page($param['page'])->limit(10)->select()->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $val['goods_info'] = json_decode($val['goods_info'],true);
            }
        }
        return success('',$data);
    }

    /**
     * 订单详情
     */
    public function orderDetail()
    {
        $param = request()->param();
        $data = Db::name('score_order')->where('id',$param['id'])->find();
        $data['goods_info'] = json_decode($data['goods_info'],true);
        $data['create_time'] = datetime($data['create_time']);
        $data['pay_time'] = datetime($data['pay_time']);
        if (!empty($data['address'])) {
            $data['address'] = json_decode($data['address'],true);
        }
        return success('',$data);
    }

    /**
     * 订单提交
     */
    public function makeOrder()
    {
        if (request()->isPost()) {
            $param = request()->param();
            $goods = Db::name('score_goods')->field('id,title,thumb,price,yun_money,goods_type')
                ->where('id',$param['id'])->find();
            $user = Db::name('user')->where('id',JWT_UID)->find();
            $yun = 0;
            if (empty($address['is_mail'])) {
                $yun = $goods['yun_money'];
            }
            $total = $goods['price']+$yun;
            if ($user['score'] < $total) {
                return error('积分不足');
            }
            if (empty($param['address_id'])) {
                return error('请选择地址');
            }
            $address = Db::name('addr')
                ->field('id,region,address,user_name,mobile')
                ->where('id',$param['address_id'])
                ->find();
            $add = [
                'uid' => JWT_UID,
                'order_no' => date('YmdHis').rand(1000,9999),
                'goods_id' => $param['id'],
                'goods_info' => json_encode($goods,JSON_UNESCAPED_UNICODE),
                'amount' => $total,
                'yun' => $yun,
                'create_time' => time(),
                'pay_time' => time(),
                'address' => json_encode($address,JSON_UNESCAPED_UNICODE),
            ];
            if (!empty($param['remark'])) {
                $add['remark'] = $param['remark'];
            }
            $orderId = Db::name('score_order')->insertGetId($add);
            if (empty($orderId)) {
                return error('支付失败');
            }
            Db::name('user')->where('id',$add['uid'])->dec('score',intval($add['amount']))->update();
            Db::name('score_goods')->where('id',$param['id'])->inc('sales')->update();
            //积分记录
            Db::name('score_log')->insert([
                'uid' => JWT_UID,
                'title' => '兑换商品',
                'type' => 2,
                'num' => intval($total),
                'create_time' => time()
            ]);
            return success('支付成功',['order_id'=>$orderId]);
        }
    }

    /**
     * 积分明细
     */
    public function scoreLog()
    {
        $param = get_params();
        $data = Db::name('score_log')->where(['uid'=>JWT_UID])
            ->order('id desc')->page($param['page'])->limit(10)->select()->toArray();
        if (!empty($data)) {
            foreach ($data as &$val) {
                $val['create_time'] = datetime($val['create_time']);
            }
        }
        return success('',$data);
    }

    /**
     * 选择设备
     */
    public function selDevice()
    {
        $param = get_params();
        if (empty($param['id'])) {
            return error('ID参数为空');
        }
        $order = Db::name('score_order')->where('id',$param['id'])->find();
        $goods_info = json_decode($order['goods_info'],true);
        $device = Db::name('user_device')->alias('u')
            ->join('device d','u.device_id=d.id')
            ->field('u.id,d.deviceId,d.device_status,d.order_id')
            ->where(['u.uid'=>JWT_UID,'u.delete_time'=>0])
            ->order('u.id desc')
            ->select()->toArray();
        if (!empty($device)) {
            foreach ($device as $key => $val) {
                $k = $key+1;
                $device[$key]['title'] = '净水器'.$k;
                //净水器下面的套餐
                $current = Db::name('order')->where('id',$val['order_id'])->find();
                $package = Db::name('order')->where([
                    'deviceId'=>$val['deviceId'],
                    'type'=>$goods_info['goods_type'],
                    'delete_time'=>0,
                    'status'=>1,
                ])->order('id asc')->select()->toArray();
                if (!empty($package)) {
                    foreach ($package as &$v) {
                        if ($v['id'] == $current['id']) {
                            if($current['after'] > 0){
                                $v['is_use'] = 1;//使用中
                            } else {
                                $v['is_use'] = 3;
                            }
                        } else {
                            if($v['after'] > 0){
                                $v['is_use'] = 2; //未使用
                            } else {
                                $v['is_use'] = 3; //已用完
                            }
                        }
                        $v['content'] = json_decode($v['content'],true);
                    }
                }
                $device[$key]['package_list'] = $package;
            }
        }
        return success('',$device);
    }

    /**
     * 选择设备套餐
     */
    public function selDevicePackage()
    {
        $param = get_params();
        $score_order = Db::name('score_order')->where('id',$param['order_id'])->find();
        if (!empty($score_order['confirm_time'])) {
            return error('请勿重复使用');
        }
        $goods_info = json_decode($score_order['goods_info'],true);
        $order = Db::name('order')->where('id',$param['id'])->find();

        Db::name('order')->where('id',$param['id'])->inc('total',intval($goods_info['nums']))->update();
        Db::name('order')->where('id',$param['id'])->inc('after',intval($goods_info['nums']))->update();
        //判断设备是否正在使用该套餐
        $device=Db::name("device")->where("deviceId",$order["deviceId"])->find();
        if ($device['order_id'] == $order['id']) {
            if ($device['type'] == 1) {
                $save['sy_water'] = $device['sy_water']+$param['content'];
            } else {
                $save['day'] = $device['day']+$param['content'];
            }
            $save['update_time'] = time();
            Db::name("device")->where("id",$device["id"])->update($save);
        }
        if ($device['lock_status'] == 2) {
            //发送解锁指令
            $work = new Work();
            $send_data['deviceId'] = $device['deviceId'];
            $send_data['lock_status'] = "1";
            $lock_data = [
                'data' => $send_data
            ];
            $work::device_lock_s($device['deviceId'],$lock_data);
        }
        Db::name('score_order')->where('id',$param['order_id'])->update(['status'=>2,'confirm_time'=>time()]);
        return success('赠送成功');
    }
}